import Vue from 'vue'
import md5 from 'blueimp-md5'

export default function() {
  Vue.prototype.upload = function(base64, id, description, table) {

    let progress = this.$f7.dialog.progress('图片正在上传', 0)

    const file = base64ToBlob(base64)

    const timestamp = Date.now()
    let formdata = new FormData()
    formdata.append('file', file)
    formdata.append('description', description)
    formdata.append('table', table)

    let xhr = new XMLHttpRequest()
    xhr.open('post', `${window.baseUrl}/upload?timestamp=${timestamp}&id=${id}`, true)
    xhr.setRequestHeader('authcode', md5(`${timestamp}tpgj`))
    xhr.onreadystatechange = () => {
      if (xhr.readyState == 4 && xhr.status == 200) {
        const res = JSON.parse(xhr.response)
        if (res.code === 1) {
          this.$f7.toast.show({ text: '图片上传成功' })
        } else {
          this.$f7.toast.show({ text: '图片上传失败' })
        }
        progress.close()
      }
      if (xhr.readyState == 4 && xhr.status == 500) {
        this.$f7.toast.show({ text: '图片上传失败' })
        progress.close()
      }
    }
    xhr.upload.onprogress = function(e) {
      progress.setProgress(parseInt((e.loaded / e.total) * 100), 50)
    }
    xhr.onerror = xhr.upload.onerror = () => {
      this.$f7.toast.show({ text: '图片上传失败' })
      progress.close()
    }
    xhr.send(formdata)
  }

  function base64ToBlob(urlData) {
    var bytes = window.atob(urlData);
    // 处理异常,将ascii码小于0的转换为大于0
    var ab = new ArrayBuffer(bytes.length);
    // 生成视图（直接针对内存）：8位无符号整数，长度1个字节
    var ia = new Uint8Array(ab);

    for (var i = 0; i < bytes.length; i++) {
      ia[i] = bytes.charCodeAt(i);
    }

    var blob = new Blob([ab], {
      type: 'image/jpeg'
    });

    return blob
  }
}